package com.xxx.mch.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.xxx.mch.domain.dto.TaskScoreTemplateDto;
import com.xxx.mch.domain.po.BusinessStatistics;
import com.xxx.mch.domain.request.QueryScoreRequest;
import com.xxx.mch.exception.BusinessException;
import com.xxx.mch.service.TaskScoreService;
import com.xxx.mch.service.TotalScoreService;
import com.xxx.mch.service.impl.BusinessStatisticsImpl;
import com.xxx.mch.utils.WrapMapper;
import com.xxx.mch.utils.Wrapper;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 业务统计
 *
 * @author FengHaixin
 * @description 一句话描述该文件的用途
 * @date 2020-02-25
 */
@Slf4j
@RestController
@RequestMapping ("businessStatistics")
public class BusinessStatisticsController
{

    @Autowired
    private BusinessStatisticsImpl businessStatisticsImpl;

    @Autowired
    private TaskScoreService taskScoreService;

    @Resource
    private TotalScoreService totalScoreService;


    @GetMapping (produces = MediaType.APPLICATION_JSON_VALUE)
    public Wrapper<List<LinkedHashMap<String, String>>> getList(@ModelAttribute @Validated QueryScoreRequest queryScoreRequest)
    {
        List<LinkedHashMap<String, String>> linkedHashMaps = businessStatisticsImpl.queryBusinessStatistics(queryScoreRequest.getDate(),
                                                                                                            queryScoreRequest.getDeptId(),
                                                                                                            null);
        return WrapMapper.ok(linkedHashMaps);
    }


    @GetMapping (value = "award", produces = MediaType.APPLICATION_JSON_VALUE)
    public Wrapper<String> award(@RequestParam ("month") String month)
    {
        totalScoreService.calculateAward(month, 1);
        return WrapMapper.ok();
    }


    @PostMapping (produces = MediaType.APPLICATION_JSON_VALUE)
    public Wrapper<String> saveBusinessStatistics(@RequestBody BusinessStatistics bs)
    {
        businessStatisticsImpl.saveBusinessStatistics(bs);
        return WrapMapper.ok();
    }


    @GetMapping (value = "header", produces = MediaType.APPLICATION_JSON_VALUE)
    public Wrapper<List<TaskScoreTemplateDto>> getHeaderTaskTemplate()
    {
        List<TaskScoreTemplateDto> list = taskScoreService.getTaskTemplate(null, 2, null, true);
        return WrapMapper.ok(list);
    }


    @GetMapping (value = "export")
    public void export(@ModelAttribute @Validated QueryScoreRequest queryScoreRequest, HttpServletResponse response) throws Exception
    {
        queryScoreRequest.setPageSize(10000);
        simpleWrite(queryScoreRequest, response);
    }


    private void simpleWrite(QueryScoreRequest queryScoreRequest, HttpServletResponse response) throws IOException
    {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition",
                           "attachment;filename=" + URLEncoder.encode("考核统计表-" + queryScoreRequest.getDate(), "UTF-8")
                                   + ExcelTypeEnum.XLSX.getValue());
        try
        {
            // 动态添加 表头 headList --> 所有表头行集合
            List<List<String>> headList = new ArrayList<>();

            List<TaskScoreTemplateDto> headDataList = taskScoreService.getTaskTemplate(null, 2, null, true);

            List<String> headTitle = new ArrayList<>();
            headTitle.add("姓名");
            headList.add(headTitle);

            headTitle = new ArrayList<>();
            headTitle.add("部门");
            headList.add(headTitle);
            List<String> keys = new ArrayList<>();
            //这里聚合下
            for (TaskScoreTemplateDto templateDto : headDataList)
            {
                List<String> headTitle0 = new ArrayList<>();
                headTitle0.add(templateDto.getName());
                headTitle0.add("完成量");
                headList.add(headTitle0);
                keys.add(templateDto.getId() + "-finished");

                    List<String> headTitle1 = new ArrayList<>();
                    headTitle1.add(templateDto.getName());
                    headTitle1.add("采用量");
                    keys.add(templateDto.getId() + "-used");
                    headList.add(headTitle1);

            }

            List<String> headTitle1 = new ArrayList<>();
            headTitle1.add("归档");
            headList.add(headTitle1);

            List<String> headTitle2 = new ArrayList<>();
            headTitle2.add("得分");
            headTitle2.add("定量分");
            headList.add(headTitle2);

            List<String> headTitle3 = new ArrayList<>();
            headTitle3.add("得分");
            headTitle3.add("定性分");
            headList.add(headTitle3);

            List<String> headTitle4 = new ArrayList<>();
            headTitle4.add("得分");
            headTitle4.add("总分");
            headList.add(headTitle4);

            List<String> headTitle5 = new ArrayList<>();
            headTitle5.add("本月奖金(元)");
            headList.add(headTitle5);

            List<String> headTitle6 = new ArrayList<>();
            headTitle6.add("阅读量");
            headList.add(headTitle6);

            List<String> headTitle7 = new ArrayList<>();
            headTitle7.add("获奖量");
            headList.add(headTitle7);

            List<String> headTitle8 = new ArrayList<>();
            headTitle8.add("表扬量");
            headList.add(headTitle8);

            List<String> headTitle9 = new ArrayList<>();
            headTitle9.add("其他量");
            headList.add(headTitle9);

            List<String> headTitle10 = new ArrayList<>();
            headTitle10.add("本月积分");
            headList.add(headTitle10);

            List<String> headTitle11 = new ArrayList<>();
            headTitle11.add("累计积分");
            headList.add(headTitle11);



            // 所有行的集合
            List<List<Object>> list = new ArrayList<>();

            List<LinkedHashMap<String, String>> dataList = businessStatisticsImpl.queryBusinessStatistics(queryScoreRequest.getDate(),
                                                                                                          queryScoreRequest.getDeptId(),
                                                                                                          null);
            for (LinkedHashMap<String, String> data : dataList)
            {
                // 第 n 行的数据
                List<Object> row = new ArrayList<>();

                String username = data.get("username");
                row.add(username);

                String deptName = data.get("dept_name");
                row.add(deptName);

                for (String key : keys)
                {
                    Object obj = data.get(key);
                    if (obj instanceof BigDecimal)
                    {
                        row.add(obj);
                    }
                }
                row.add(data.get("archiveCount"));
                row.add(data.get("qualityScore"));
                row.add(data.get("determinationScore"));
                row.add(data.get("totalScore"));
                row.add(data.get("money"));
                row.add(data.get("readCount"));
                row.add(data.get("awardCount"));
                row.add(data.get("praiseCount"));
                row.add(data.get("otherCount"));
                row.add(data.get("points"));
                row.add(data.get("accumulativePoints"));
                list.add(row);
            }
            EasyExcel.write(response.getOutputStream()).head(headList).sheet(queryScoreRequest.getDate()).doWrite(list);
        }
        catch (Exception e)
        {
            log.error("生成excel失败", e);
            throw new BusinessException("生成excel失败");
        }

    }
}
